<template>
  <div class="box">
    <div class="left">
      <div class="ship">
        <div class="search">
          <SearchForm
            ref="searchFormRef"
            :formInputs="state.formInputs"
            @submit="search"
          />
        </div>
        <div class="info">
          <img :src="fileShow(state.ship?.pic)" />
          <div class="mark">
            <p>
              <span>船号：{{ state.ship?.name }}</span>
              <span>类型：{{ state.ship?.type }}</span>
            </p>
            <p>施工工序：{{ state.order?.workFlows }}</p>
            <p>
              总管：{{ state.order?.manager }}
              {{
                state.order?.managerTel ? `(${state.order?.managerTel})` : ""
              }}
            </p>
            <p>
              进场时间：
              {{ dayjs(state.order?.enterTime).format("YYYY-MM-DD") }}
            </p>
            <p>
              出场时间：
              {{
                state.order?.outTime
                  ? dayjs(state.order?.outTime).format("YYYY-MM-DD")
                  : "-"
              }}
            </p>
          </div>
        </div>
      </div>
      <div class="group">
        <ColumnSearch
          title="单船修理碳排放量统计"
          :formInputs="state.pieSearch"
          :obj="state.pieObj"
          @submit="onPieSubmit"
        >
          <a-button type="primary" size="small" @click="infoClick"
            >详情</a-button
          >
        </ColumnSearch>
        <div class="pie" ref="pieRef"></div>
      </div>
    </div>
    <div class="right">
      <div class="chart">
        <ColumnSearch
          title="能源碳排放监控"
          :formInputs="state.c1Search"
          :obj="state.c1Obj"
          @submit="onC1Submit"
        />
        <div ref="c1Ref" class="column"></div>
      </div>
      <div class="chart">
        <ColumnSearch
          title="单船研究数据监控"
          :formInputs="state.c2Search"
          :obj="state.c2Obj"
          @submit="onC2Submit"
        />
        <div ref="c2Ref" class="column"></div>
      </div>
    </div>
  </div>
  <a-modal
    title="单船修理碳排放量统计"
    :visible="!!state.repair"
    width="90%"
    :footer="null"
    :destroyOnClose="true"
    centered
    @cancel="
      () => {
        state.repair = null;
      }
    "
  >
    <Page :repair="state.repair" :type="1" />
  </a-modal>
</template>
<script setup>
import {
  getCurrentInstance,
  reactive,
  ref,
  onMounted,
  watch,
  toRaw,
} from "vue";
import * as echarts from "echarts";
import _ from "lodash";
import ColumnSearch from "@/components/ColumnSearch.vue";
import SearchForm from "@/components/SearchForm.vue";
import { fileShow } from "@/utils/fileShow.js";
import dayjs from "dayjs";
import Page from "./ShipEmissionReport/index.vue";

const { proxy } = getCurrentInstance();
const searchFormRef = ref();

const state = reactive({
  formInputs: [
    {
      label: "船舶",
      type: "select",
      name: "shipRepairId",
      options: [],
      style: { width: "200px" },
    },
  ],
  ship: null,
  order: null,
  // 驱动单船能源1-4级数据弹窗展开
  repair: null,
  pieSearch: [
    {
      label: "指南",
      type: "select",
      name: "ratio",
      options: [
        { label: "因子指标", value: 0 },
        { label: "船舶及海洋工程装备造修企业碳排放核算指南", value: 1 },
      ],
    },
  ],
  pieObj: { ratio: 0 },
  // 单船碳排一级数据
  stat: null,
  c1Search: [
    {
      label: "指南",
      type: "select",
      name: "ratio",
      style: { width: "100px" },
      options: [
        { label: "因子指标", value: 0 },
        { label: "船舶及海洋工程装备造修企业碳排放核算指南", value: 1 },
      ],
    },
    {
      label: "能源",
      type: "select",
      name: "type",
      options: [
        { label: "电力", value: "电力" },
        { label: "液化天然气", value: "液化天然气" },
        { label: "二氧化碳", value: "二氧化碳" },
        { label: "柴油", value: "柴油" },
      ],
    },
    {
      label: "时间",
      type: "dateRange",
      name: "range",
    },
  ],
  c1Obj: {
    ratio: 0,
    type: "电力",
    range: [],
  },
  c2Search: [
    {
      label: "指南",
      type: "select",
      name: "ratio",
      style: { width: "100px" },
      options: [
        { label: "因子指标", value: 0 },
        { label: "船舶及海洋工程装备造修企业碳排放核算指南", value: 1 },
      ],
    },
    {
      label: "时间",
      type: "dateRange",
      name: "range",
    },
  ],
  c2Obj: { ratio: 0, range: [] },
});
const pieRef = ref();
const c1Ref = ref();
const c2Ref = ref();

let pieChart, c1Chart, c2Chart;
onMounted(async () => {
  pieChart = echarts.init(pieRef.value);

  const { success, data } = await proxy.$axios.get("/ship_repair/dict");
  if (success) {
    const one = _.find(state.formInputs, { name: "shipRepairId" });
    one.options = _.map(data, (o) => ({
      label: o.shipName,
      value: JSON.stringify({ shipId: o.shipId, repairId: o.repairId }),
    }));

    const firstId = one.options[0].value;
    searchFormRef.value.changeFieldValue("shipRepairId", firstId);
    search({ shipRepairId: firstId });
  }

  c1Chart = echarts.init(c1Ref.value);
  getC1();
  c2Chart = echarts.init(c2Ref.value);
  getC2();

  // 监听窗口大小变化
  window.addEventListener("resize", function () {
    // 当窗口大小变化时，重新设置图表的大小
    pieChart.resize();
    c1Chart.resize();
    c2Chart.resize();
  });
});

const search = ({ shipRepairId }) => {
  const { shipId, repairId } = JSON.parse(shipRepairId);
  // 获取船舶信息
  proxy.$axios.get(`/ship/${shipId}`).then(({ success, data }) => {
    if (success) {
      state.ship = data;
    }
  });

  // 获取维修单详情
  proxy.$axios.get(`/ship_repair/${repairId}`).then(({ success, data }) => {
    if (success) {
      state.order = data;
    }
  });

  // 获取船舶单船统计一级能源信息
  proxy.$axios
    .get("/workflow/stat/first", { params: { repairId } })
    .then(({ success, data }) => {
      if (success) {
        state.stat = data.list;
      }
    });
};

const onPieSubmit = ({ ratio }) => {
  state.pieObj.ratio = ratio;
};

watch(
  () => [state.stat, state.pieObj.ratio],
  ([stat, ratio]) => {
    if (stat) {
      const db = _.map(stat, (o) => {
        let value = null;
        if (ratio === 0) {
          value = o.cshen;
        } else if (ratio === 1) {
          value = o.cocean;
        }
        return {
          name: o.energyCategory,
          value,
        };
      });
      const total = _.sumBy(db, "value");
      pieChart.setOption({
        title: {
          zlevel: 0,
          text: `总碳排放量\n${total.toFixed(2)}tCO2`,
          top: "center",
          left: "center",
          textStyle: {
            color: "white",
          },
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          bottom: 0,
          left: "center",
          textStyle: { color: "#fff" },
        },
        series: [
          {
            name: "能源类型",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            data: db,
          },
        ],
      });
    }
  },
  { deep: true }
);

// 详情点开，弹出单船工序1-4级展示
const infoClick = () => {
  const order = toRaw(state.order);
  const ship = toRaw(state.ship);
  state.repair = {
    repairId: order.id,
    shipId: order.shipId,
    shipName: ship.name,
  };
};

const getC1 = async () => {
  const { ratio, type, range } = state.c1Obj;
  let beginTime,
    endTime = undefined;
  if (range?.length === 2) {
    beginTime = range[0].format("YYYY-MM-DD");
    endTime = range[1].format("YYYY-MM-DD");
  }
  const { success, data } = await proxy.$axios.get("/workflow_chart/energy", {
    params: {
      CType: ratio,
      energyCategory: type,
      beginTime,
      endTime,
    },
  });
  if (success) {
    const names = [],
      values = [];
    _.each(data, (o) => {
      names.push(o.shipName);
      values.push(o.value);
    });

    // 单位
    const unit = "t";

    c1Chart.setOption({
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        valueFormatter: (value) => `${value.toFixed(2)}(${unit})`,
      },
      xAxis: [
        {
          type: "category",
          data: names,
          axisTick: {
            alignWithLabel: true,
          },
        },
      ],
      yAxis: {
        type: "value",
        axisLabel: {
          formatter: `{value} ${unit}`,
        },
      },
      series: [
        {
          type: "bar",
          barWidth: "20px",
          data: values,
        },
      ],
    });
  }
};

const onC1Submit = (values) => {
  state.c1Obj = values;
  getC1();
};

const getC2 = async () => {
  const { ratio, range } = state.c2Obj;
  let beginTime,
    endTime = undefined;
  if (range?.length === 2) {
    beginTime = range[0].format("YYYY-MM-DD");
    endTime = range[1].format("YYYY-MM-DD");
  }
  const { success, data } = await proxy.$axios.get("/workflow_chart/ship", {
    params: {
      CType: ratio,
      beginTime,
      endTime,
    },
  });
  if (success) {
    const names = [],
      values = [];
    _.each(data, (o) => {
      names.push(o.shipName);
      values.push(o.value);
    });

    const unit = "t";

    c2Chart.setOption({
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        valueFormatter: (value) => `${value.toFixed(2)}(${unit})`,
      },
      xAxis: [
        {
          type: "category",
          data: names,
          axisTick: {
            alignWithLabel: true,
          },
        },
      ],
      yAxis: {
        type: "value",
        axisLabel: {
          formatter: `{value} ${unit}`,
        },
      },
      series: [
        {
          type: "bar",
          barWidth: "20px",
          data: values,
        },
      ],
    });
  }
};

const onC2Submit = (values) => {
  state.c2Obj = values;
  getC2();
};
</script>
<style lang="less" scoped>
.box {
  padding: 5px;
  height: 100%;
  display: flex;

  table {
    width: 100%;
    border: 1px solid #f8f8f8;
  }

  th,
  td {
    text-align: center;
    border: 1px solid #f8f8f8;
    padding: 4px;
  }

  .left {
    width: 50%;
    height: 100%;
    padding: 5px 2.5px;
    display: flex;
    flex-direction: column;

    .ship {
      width: 100%;
      height: calc(50% - 3px);
      border: 1px solid #f8f8f8;
      padding: 1rem;
      margin-bottom: 6px;

      .search {
        height: 40px;
        border-bottom: 1px dashed #f8f8f8;
      }

      .info {
        margin-top: 8px;
        display: flex;
        height: calc(100% - 48px);

        img {
          width: 40%;
        }

        .mark {
          width: 60%;
          height: 100%;
          overflow-y: auto;
          padding-left: 1rem;
          padding: 1rem;

          p {
            width: 100%;

            span {
              width: 50%;
              display: inline-block;
            }
          }
        }
      }
    }

    .group {
      flex: 1;
      border: 1px solid #f8f8f8;
      padding: 5px;

      .pie {
        height: calc(100% - 34.2px);
      }
    }
  }

  .right {
    width: 50%;
    height: 100%;
    padding: 5px 2.5px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .chart {
      width: 100%;
      height: calc(50% - 3px);
      border: 1px solid #f8f8f8;
      display: flex;
      flex-direction: column;

      .column {
        flex: 1;
      }
    }
  }
}
</style>
